//@version=5
indicator("VitAlgo", overlay=true, precision=0, explicit_plot_zorder=true, max_labels_count=500)

// Get user input
sensitivity = input.float(5.5, "Sensitivity (0.5 - 12)", 0.5, 12, step=0.05, group = 'Settings')

f_typee = input.string(defval='Trading', options=['Sniper Signals', 'Trading'], title='Signal Mode', group = 'Settings')

ShowSmartTrail = input.bool(false, 'Smart Trail      ', inline = 'overlayLine1', group = 'Settings')
maj = input(true, title='TP Points', inline = 'overlayLine1', group = 'Settings')

ShowTEX = input.bool(false, 'Reversal Signal    ', inline = 'overlayLine2', group = 'Settings')
show_ha = input.bool(false, 'Trend Tracker', inline = 'overlayLine2', group = 'Settings')

enableSR   = input(false, 'Support/Resistance  ', inline = 'overlayLine3', group = 'Settings')
usePsar     = input.bool(false, 'PSAR', inline = 'overlayLine3', group = 'Settings')

show_rev = input.bool(true, 'Reversal Cloud    ', inline = 'overlayLine4', group = 'Settings')
Show_rangefilter = input.bool(false, 'Trend Catcher', inline = 'overlayLine4', group = 'Settings')

Show_SuperIchi = input.bool(false, 'SuperIchi      ', inline = 'overlayLine5', group = 'Settings')
Show_TBO = input.bool(true, 'Small Signals', inline = 'overlayLine5', group = 'Settings')



// Functions
supertrend(_src, factor, atrLen) =>
	atrat = ta.atr(atrLen)
	upperBand = _src + factor * atrat
	lowerBand = _src - factor * atrat
	prevLowerBand = nz(lowerBand[1])
	prevUpperBand = nz(upperBand[1])
	lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
	upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
	int direction = na
	float superTrend = na
	prevSuperTrend = superTrend[1]
	if na(atrat[1])
		direction := 1
	else if prevSuperTrend == prevUpperBand
		direction := close > upperBand ? -1 : 1
	else
		direction := close < lowerBand ? 1 : -1
	superTrend := direction == -1 ? lowerBand : upperBand
	[superTrend, direction]
// Get Components
ocAvg       = math.avg(open, close)
ema1        = ta.ema(high, 9)
ema2        = ta.ema(high, 12)
ema3        = ta.ema(high, 15)
ema4        = ta.ema(high, 18)
sma1        = ta.sma(close, 5)
sma2        = ta.sma(close, 6)
sma3        = ta.sma(close, 7)
sma4        = ta.sma(close, 8)
sma5        = ta.sma(close, 9)
sma6        = ta.sma(close, 10)
sma7        = ta.sma(close, 11)
sma8        = ta.sma(close, 12)
sma9        = ta.sma(close, 13)
sma10       = ta.sma(close, 14)
sma11       = ta.sma(close, 15)
sma12       = ta.sma(close, 16)
sma13       = ta.sma(close, 17)
sma14       = ta.sma(close, 18)
sma15       = ta.sma(close, 19)
sma16       = ta.sma(close, 20)
psar        = ta.sar(0.02, 0.02, 0.2)
[supertrend, direction] = supertrend(close, sensitivity, 11)
barsL       = 10
barsR       = 10
pivotHigh = fixnan(ta.pivothigh(barsL, barsR)[1])
pivotLow = fixnan(ta.pivotlow(barsL, barsR)[1])
// Colors
green       = #04994b, green2   = #15c02a
red         = #b4060d, red2     = #ff0002


p5 = plot(ocAvg, "", na, editable=false)
p6 = plot(psar, "PSAR", usePsar ? (psar < ocAvg ? green : red) : na, 1, plot.style_circles, editable=false)
fill(p5, p6, usePsar ? (psar < ocAvg ? color.new(green, 90) : color.new(red, 90)) : na, editable=false)
y1 = low - (ta.atr(30) * 2)
y2 = high + (ta.atr(30) * 2)
bull = ta.crossover(close, supertrend) and close >= sma9
bear = ta.crossunder(close, supertrend) and close <= sma9
buy  = bull and f_typee == 'Trading' ? label.new(bar_index, y1, "▲", xloc.bar_index, yloc.price, #04994b, label.style_label_up, color.white, size.normal) : na
sell = bear and f_typee == 'Trading' ? label.new(bar_index, y2, "▼", xloc.bar_index, yloc.price, #b4060d, label.style_label_down, color.white, size.normal) : na

// Strong TP Points //

maj_qual = 13
maj_len = 40
min_qual = 5
min_len = 5
min = false

selll = 0.0
buyy = 0.0

lele(qual, len) =>
    bindex = 0.0
    sindex = 0.0
    bindex := nz(bindex[1], 0)
    sindex := nz(sindex[1], 0)
    ret = 0
    if close > close[4]
        bindex += 1
        bindex
    if close < close[4]
        sindex += 1
        sindex
    if bindex > qual and close < open and high >= ta.highest(high, len)
        bindex := 0
        ret := -1
        ret
    if sindex > qual and close > open and low <= ta.lowest(low, len)
        sindex := 0
        ret := 1
        ret
    return_1 = ret
    return_1

major = lele(maj_qual, maj_len)
minor = lele(min_qual, min_len)

if minor == -1 and min == true
    selll := 1
    selll
if major == -1 and maj == true
    selll := 2
    selll
if major == -1 and maj == true and minor == -1 and min == true
    selll := 3
    selll

if minor == 1 and min == true
    buyy := 1
    buyy
if major == 1 and maj == true
    buyy := 2
    buyy
if major == 1 and maj == true and minor == 1 and min == true
    buyy := 3
    buyy

plotshape(selll == 2, style=shape.xcross, location=location.abovebar, color=color.new(#354996, 0), textcolor=color.new(color.white, 0), offset=0)

plotshape(buyy == 2, style=shape.xcross, location=location.belowbar, color=color.new(#354996, 0), textcolor=color.new(color.white, 0), offset=0)

// Ha Market Bias //

tf(_res, _exp, gaps_on) =>
    gaps_on == 0 ? request.security(syminfo.tickerid, _res, _exp) : gaps_on == true ? request.security(syminfo.tickerid, _res, _exp, barmerge.gaps_on, barmerge.lookahead_off) : request.security(syminfo.tickerid, _res, _exp, barmerge.gaps_off, barmerge.lookahead_off)

ha_htf = ''
ha_len = 100
ha_len2 = 100

// Calculations {
o = ta.ema(open, ha_len)
c = ta.ema(close, ha_len)
h = ta.ema(high, ha_len)
l = ta.ema(low, ha_len)

haclose = tf(ha_htf, (o + h + l + c) / 4, 0)
xhaopen = tf(ha_htf, (o + c) / 2, 0)
haopen = na(xhaopen[1]) ? (o + c) / 2 : (xhaopen[1] + haclose[1]) / 2
hahigh = math.max(h, math.max(haopen, haclose))
halow = math.min(l, math.min(haopen, haclose))


o2 = tf(ha_htf, ta.ema(haopen, ha_len2), 0)
c2 = tf(ha_htf, ta.ema(haclose, ha_len2), 0)
h2 = tf(ha_htf, ta.ema(hahigh, ha_len2), 0)
l2 = tf(ha_htf, ta.ema(halow, ha_len2), 0)

ha_avg = (h2 + l2) / 2
// }
    
// Oscillator {
osc_len = 7

osc_bias = 100 *(c2 - o2)
osc_smooth = ta.ema(osc_bias, osc_len)

sigcolor = 
  (osc_bias > 0) and (osc_bias >= osc_smooth) ? color.new(color.lime, 35) : 
  (osc_bias > 0) and (osc_bias < osc_smooth) ? color.new(color.lime, 75) : 
  (osc_bias < 0) and (osc_bias <= osc_smooth) ? color.new(color.red, 35) : 
  (osc_bias < 0) and (osc_bias > osc_smooth) ? color.new(color.red, 75) :
  na
// }

// Plots {
p_h = plot(h2, "Bias High", color=color(na), display=display.none, editable=false)
p_l = plot(l2, "Bias Low", color=color(na), display=display.none, editable=false)
p_avg = plot(ha_avg, "Bias Avergae", color=color(na), display=display.none, editable=false)


fill(p_l, p_h, show_ha ? sigcolor : na)
col = o2 > c2 ? color.red : color.lime
// }

// Range Filter DW


//---------------------Range Filter----------------------------------------------------------------------------------------------------------------------

//Conditional Sampling EMA Function 
Cond_EMA(x, cond, n) =>
    var val = array.new_float(0)
    var ema_val = array.new_float(1)
    if cond
        array.push(val, x)
        if array.size(val) > 1
            array.remove(val, 0)
        if na(array.get(ema_val, 0))
            array.fill(ema_val, array.get(val, 0))
        array.set(ema_val, 0, (array.get(val, 0) - array.get(ema_val, 0)) * (2 / (n + 1)) + array.get(ema_val, 0))
    EMA = array.get(ema_val, 0)
    EMA

//Conditional Sampling SMA Function
Cond_SMA(x, cond, n) =>
    var vals = array.new_float(0)
    if cond
        array.push(vals, x)
        if array.size(vals) > n
            array.remove(vals, 0)
    SMA = array.avg(vals)
    SMA

//Standard Deviation Function
Stdev(x, n) =>
    math.sqrt(Cond_SMA(math.pow(x, 2), 1, n) - math.pow(Cond_SMA(x, 1, n), 2))

//Range Size Function
rng_size(x, scale, qty, n) =>
    ATR = Cond_EMA(ta.tr(true), 1, n)
    AC = Cond_EMA(math.abs(x - x[1]), 1, n)
    SD = Stdev(x, n)
    rng_size = scale == 'Pips' ? qty * 0.0001 : scale == 'Points' ? qty * syminfo.pointvalue : scale == '% of Price' ? close * qty / 100 : scale == 'ATR' ? qty * ATR : scale == 'Average Change' ? qty * AC : scale == 'Standard Deviation' ? qty * SD : scale == 'Ticks' ? qty * syminfo.mintick : qty
    rng_size

//Two Type Range Filter Function
rng_filt(h, l, rng_, n, type, smooth, sn, av_rf, av_n) =>
    rng_smooth = Cond_EMA(rng_, 1, sn)
    r = smooth ? rng_smooth : rng_
    var rfilt = array.new_float(2, (h + l) / 2)
    array.set(rfilt, 1, array.get(rfilt, 0))
    if type == 'Type 1'
        if h - r > array.get(rfilt, 1)
            array.set(rfilt, 0, h - r)
        if l + r < array.get(rfilt, 1)
            array.set(rfilt, 0, l + r)
    if type == 'Type 2'
        if h >= array.get(rfilt, 1) + r
            array.set(rfilt, 0, array.get(rfilt, 1) + math.floor(math.abs(h - array.get(rfilt, 1)) / r) * r)
        if l <= array.get(rfilt, 1) - r
            array.set(rfilt, 0, array.get(rfilt, 1) - math.floor(math.abs(l - array.get(rfilt, 1)) / r) * r)
    rng_filt1 = array.get(rfilt, 0)
    hi_band1 = rng_filt1 + r
    lo_band1 = rng_filt1 - r
    rng_filt2 = Cond_EMA(rng_filt1, rng_filt1 != rng_filt1[1], av_n)
    hi_band2 = Cond_EMA(hi_band1, rng_filt1 != rng_filt1[1], av_n)
    lo_band2 = Cond_EMA(lo_band1, rng_filt1 != rng_filt1[1], av_n)
    rng_filt = av_rf ? rng_filt2 : rng_filt1
    hi_band = av_rf ? hi_band2 : hi_band1
    lo_band = av_rf ? lo_band2 : lo_band1
    [hi_band, lo_band, rng_filt]

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Inputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//Filter Type
f_type = 'Type 2'

//Movement Source
mov_src = 'Close'

//Range Size Inputs
rng_qty = 2.618
rng_scale = 'Average Change'

//Range Period
rng_per = 14

//Range Smoothing Inputs
smooth_range = true
smooth_per = 27

//Filter Value Averaging Inputs
av_vals = false
av_samples = 2

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Definitions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//High And Low Values
h_val = mov_src == 'Wicks' ? high : close
l_val = mov_src == 'Wicks' ? low : close

//Range Filter Values
[h_band, l_band, filt] = rng_filt(h_val, l_val, rng_size((h_val + l_val) / 2, rng_scale, rng_qty, rng_per), rng_per, f_type, smooth_range, smooth_per, av_vals, av_samples)

//Direction Conditions
var fdir = 0.0
fdir := filt > filt[1] ? 1 : filt < filt[1] ? -1 : fdir
upward = fdir == 1 ? 1 : 0
downward = fdir == -1 ? 1 : 0

//Colors
filt_color = upward ? #36db7f : downward ? #be130f : #cccccc

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Outputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

//Filter Plot
filt_plot = plot(Show_rangefilter ? filt : na, color=filt_color, linewidth=3, title='Filter', transp=0)

//Bar Color

//External Trend Output
plot(fdir, editable=false, display=display.none, title='External Output - Trend Signal', transp=100)


// Superlchi + TBO 

tenkan_len  = 6
tenkan_mult = 2

kijun_len   = 5
kijun_mult  = 3.

spanB_len   = 26
spanB_mult  = 4.

offset      = 0
//------------------------------------------------------------------------------
avg(srcc,length,mult)=>
    atr = ta.atr(length)*mult
    up = hl2 + atr
    dn = hl2 - atr
    upper = 0.,lower = 0.
    upper := srcc[1] < upper[1] ? math.min(up,upper[1]) : up
    lower := srcc[1] > lower[1] ? math.max(dn,lower[1]) : dn
    
    os = 0,max = 0.,min = 0.
    os := srcc > upper ? 1 : srcc < lower ? 0 : os[1]
    spt = os == 1 ? lower : upper
    max := ta.cross(srcc,spt) ? math.max(srcc,max[1]) : os == 1 ? math.max(srcc,max[1]) : spt
    min := ta.cross(srcc,spt) ? math.min(srcc,min[1]) : os == 0 ? math.min(srcc,min[1]) : spt
    math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)

senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
tenkan_css = #2157f3
kijun_css = #ff5d00

cloud_a = color.new(color.teal,80)
cloud_b = color.new(color.red,80)

chikou_css = #7b1fa2

plot(Show_SuperIchi ? tenkan : na,'Tenkan-Sen',tenkan_css)
plot(Show_SuperIchi ? kijun : na,'Kijun-Sen',kijun_css)

plot(ta.crossover(tenkan,kijun) and Show_SuperIchi ? kijun : na,'Crossover',#2157f3,3,plot.style_circles)
plot(ta.crossunder(tenkan,kijun) and Show_SuperIchi ? kijun : na,'Crossunder',#ff5d00,3,plot.style_circles)

A = plot(Show_SuperIchi ? senkouA : na,'Senkou Span A',na,offset=offset-1)
B = plot(Show_SuperIchi ? senkouB : na,'Senkou Span B',na,offset=offset-1)
fill(A,B,senkouA > senkouB ? cloud_a : cloud_b)

plot(close,'Chikou',chikou_css,offset=-offset+1,display=display.none)

//------------------------- TBO | https://www.thebettertraders.com -----------//
// Get user input
bool  enableCustomTBO = input(false, "Enable?", "Custom trend settings are not enabled by default. The default settings loaded are not shown publicly. You have the option to enter your own custom settings as you get more familiar with the TBO.", group="CUSTOM TREND STRENGTH SETTINGS")
var   fastLen         = input.int(1, "TBO Fast", 1, group="CUSTOM TREND STRENGTH SETTINGS")
var   mediumLen       = input.int(2, "TBO Medium", 2, group="CUSTOM TREND STRENGTH SETTINGS")
var   medfastLen      = input.int(3, "TBO Med Fast", 3, group="CUSTOM TREND STRENGTH SETTINGS")
var   slowLen         = input.int(4, "TBO Slow", 4, group="CUSTOM TREND STRENGTH SETTINGS")
bool  enableRSI       = input(false, "Enable?", "Enable this if you wish to combine an RSI requirement with the TBO Long or TBO Short signal. The default settings shown here have no importance, they are just placeholders and are not significant. It is raccomended to have the RSI showing when this is enabled so you can see what kind of settings will work.", group="TBO LONG/SHORT W/ RSI")
var   shortRsiBand    = input.int(70, "Short RSI Band", 1, 100, group="TBO LONG/SHORT W/ RSI")
var   shortBandGL     = input.string("Greater Than", "Greater/Less Than", ["Greater Than", "Less Than"], group="TBO LONG/SHORT W/ RSI")
var   longRsiBand     = input.int(30, "Long RSI Band", 1, 100, group="TBO LONG/SHORT W/ RSI")
var   longBandGL      = input.string("Less Than", "Greater/Less Than", ["Greater Than", "Less Than"], group="TBO LONG/SHORT W/ RSI")
var   rsiLen          = input.int(14, "TBO Med Fast", 1, group="TBO LONG/SHORT W/ RSI")
bool  enableTP        = input(false, "Enable?", group="TAKE PROFIT SETTINGS")
var   longTPperc      = input.int(9, "TP Long %", 1, group="TAKE PROFIT SETTINGS")
var   shortTPperc     = input.int(9, "TP Short %", 1, group="TAKE PROFIT SETTINGS")
bool  static          = input(false, "Static", "If enabled will plot a signal every time volume gets greater than your defined value.", group="DHP VOLUME SCALPING")
var   volThreshold    = input.int(20000, "Volume", 1, group="DHP VOLUME SCALPING")
bool  maMultiple      = input(false, "MA Multiple", "If enabled will plot a signal every time volume gets greater than his average multiplied by your defined value.", group="DHP VOLUME SCALPING")
var   average         = input.int(20, "Average", 2, tooltip="Number of bars back used to calculate the volume's average.", group="DHP VOLUME SCALPING")
var   multipleX       = input.int(3, "Multiple X", 1, tooltip="Number of times the volume's average will be multiplied.", group="DHP VOLUME SCALPING")
// Functions
bb(src, len, mult) =>
    float basis = ta.ema(src, len)
    float dev = mult * ta.stdev(src, len)
    [basis, basis + dev, basis - dev]
[_, upperBB, lowerBB] = bb(close, 25, 1)
isLast(var1, var2) => ta.barssince(var1) < ta.barssince(var2)
// Get components
float fastTBO         = ta.ema(close, enableCustomTBO ? fastLen : 20)
float mediumTBO       = ta.ema(close, enableCustomTBO ? mediumLen : 40)
float medfastTBO      = ta.sma(close, enableCustomTBO ? medfastLen : 50)
float slowTBO         = ta.sma(close, enableCustomTBO ? slowLen : 150)
float rsi             = ta.rsi(close, rsiLen)
bool  rsiShort        = enableRSI and shortBandGL == "Greater Than" ? (rsi > shortRsiBand) : (rsi < shortRsiBand)
bool  rsiLong         = enableRSI and longBandGL == "Less Than" ? (rsi < longRsiBand) : (rsi > longRsiBand)
float vol             = volume
float volMA           = ta.sma(vol, average) * multipleX
bool  openLong        = ta.crossover(fastTBO, mediumTBO) and rsiLong,   lastLong  = ta.barssince(openLong),  long  = ta.crossover(fastTBO, mediumTBO)
bool  openShort       = ta.crossunder(fastTBO, mediumTBO) and rsiShort, lastShort = ta.barssince(openShort), short = ta.crossunder(fastTBO, mediumTBO)

// Colors
greenn  = #2FD282
pink   = #E34DED
// Plots

plotshape(Show_TBO ? openLong : na, "▲ Open Long", shape.triangleup, location.belowbar, greenn, size=size.tiny)
plotshape(Show_TBO ? openShort : na, "▼ Open Short", shape.triangledown, location.abovebar, pink, size=size.tiny)

// Smart Trail
trailType = input.string('modified', 'Trailtype', options=['modified', 'unmodified'])
ATRPeriod = input(13, 'ATR Period')
ATRFactor = input(4, 'ATR Factor')
smoothing = input(8, 'Smoothing')

norm_o = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, open)
norm_h = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, high)
norm_l = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, low)
norm_c = request.security(ticker.new(syminfo.prefix, syminfo.ticker), timeframe.period, close)
//}

//////// FUNCTIONS //////////////
//{
// Wilders ma //
Wild_ma(_src, _malength) =>
    _wild = 0.0
    _wild := nz(_wild[1]) + (_src - nz(_wild[1])) / _malength
    _wild

/////////// TRUE RANGE CALCULATIONS ///////////////// 
HiLo = math.min(norm_h - norm_l, 1.5 * nz(ta.sma(norm_h - norm_l, ATRPeriod)))

HRef = norm_l <= norm_h[1] ? norm_h - norm_c[1] : norm_h - norm_c[1] - 0.5 * (norm_l - norm_h[1])

LRef = norm_h >= norm_l[1] ? norm_c[1] - norm_l : norm_c[1] - norm_l - 0.5 * (norm_l[1] - norm_h)

trueRange = trailType == 'modified' ? math.max(HiLo, HRef, LRef) : math.max(norm_h - norm_l, math.abs(norm_h - norm_c[1]), math.abs(norm_l - norm_c[1]))
//}


/////////// TRADE LOGIC ////////////////////////
//{
loss = ATRFactor * Wild_ma(trueRange, ATRPeriod)

Up = norm_c - loss
Dn = norm_c + loss

TrendUp = Up
TrendDown = Dn
Trend = 1

TrendUp := norm_c[1] > TrendUp[1] ? math.max(Up, TrendUp[1]) : Up
TrendDown := norm_c[1] < TrendDown[1] ? math.min(Dn, TrendDown[1]) : Dn

Trend := norm_c > TrendDown[1] ? 1 : norm_c < TrendUp[1] ? -1 : nz(Trend[1], 1)
trail = Trend == 1 ? TrendUp : TrendDown

ex = 0.0
ex := ta.crossover(Trend, 0) ? norm_h : ta.crossunder(Trend, 0) ? norm_l : Trend == 1 ? math.max(ex[1], norm_h) : Trend == -1 ? math.min(ex[1], norm_l) : ex[1]
//}

// //////// PLOT TP and SL /////////////

////// FIBONACCI LEVELS ///////////
//{
state = Trend == 1 ? 'long' : 'short'

fib1Level = 61.8
fib2Level = 78.6
fib3Level = 88.6

f1 = ex + (trail - ex) * fib1Level / 100
f2 = ex + (trail - ex) * fib2Level / 100
f3 = ex + (trail - ex) * fib3Level / 100
l100 = trail + 0

fill(plot(ShowSmartTrail ? (ta.sma(trail, smoothing)) : na, 'Trailingstop', style=plot.style_line, color=Trend == 1 ? color.new(#2157f9, 0) : Trend == -1 ? color.new(#ff1100, 0) : na),
 plot( ShowSmartTrail ? (ta.sma(f2, smoothing)) : na, 'Fib 2', style=plot.style_line, display=display.none),
 color=state == 'long' ? color.new(#2157f9, 80) : state == 'short' ? color.new(#ff1100, 80) : na)
//}

// Reversal Signals

colorsr = input.string(title='Color Scheme', defval='DARK', options=['DARK', 'LIGHT'] , group = "Color Scheme")
bullcolorr = colorsr == 'DARK' ? #00DBFF : color.rgb(0, 255, 8) 
bearcolorr = colorsr == 'DARK' ? #E91E63 : color.rgb(255, 0, 0)

TE1 = input(true, 'TE - 1' , group="Money Moves [Trend Exhaustion]" , inline = "TEX")
TE2 = input(true, 'TE - 2' , group="Money Moves [Trend Exhaustion]" , inline = "TEX")
TE3 = input(true, 'TE - 3' , group="Money Moves [Trend Exhaustion]" , inline = "TEX")
//TE4 = input(true, 'TE - 4' , group="Money Moves [Trend Exhaustion]" , inline = "TEX")

rsiLengthInput = input.int(22, minval=1, title="Exhaustion Strength ", group="Money Moves [Trend Exhaustion]")
rsiSourceInput = input.source(close, "Source", group="Money Moves [Trend Exhaustion]")
maTypeInput = ta.sma(close, 14)
up66 = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
downw = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi66 = downw == 0 ? 100 : up66 == 0 ? 0 : 100 - (100 / (1 + up66 / downw))
rsiMA = maTypeInput

long1 = ta.crossover(rsi66, 30)
long2 = ta.crossover(rsi66, 20)
long3 = ta.crossover(rsi66, 15)
//long4 = ta.crossover(rsi66, 10)

// SHORT
short1 = ta.crossunder(rsi66, 70)
short2 = ta.crossunder(rsi66, 80)
short3 = ta.crossunder(rsi66, 85)
//short4 = ta.crossunder(rsi66, 90)

// LONG
plotshape(long1 and ShowTEX and TE1, "GO LONG 1", style=shape.circle, location=location.belowbar,size=size.tiny, color = color.new(bullcolorr , 60) , text="1" , textcolor = bullcolorr , editable = false)
plotshape(long2 and ShowTEX and TE2, "GO LONG 2", style=shape.circle, location=location.belowbar,size=size.tiny, color = color.new(bullcolorr , 50), text="2" , textcolor = bullcolorr , editable = false)
plotshape(long3 and ShowTEX and TE3, "GO LONG 3", style=shape.circle, location=location.belowbar,size=size.tiny, color = color.new(bullcolorr , 10), text="3", textcolor = bullcolorr , editable = false)
//plotshape(long4 and ShowTEX, "GO LONG 4", style=shape.circle, location=location.belowbar,size=size.tiny, color=color.gray, text="4")

// SHORT
plotshape(short1 and ShowTEX and TE1, "GO SHORT 1", style=shape.circle, location=location.abovebar,size=size.tiny,  color = color.new(bearcolorr , 60) , text="1" , textcolor = bearcolorr , editable = false)
plotshape(short2 and ShowTEX and TE2, "GO SHORT 2", style=shape.circle, location=location.abovebar,size=size.tiny,  color = color.new(bearcolorr , 50) , text="2" , textcolor = bearcolorr , editable = false)
plotshape(short3 and ShowTEX and TE3, "GO SHORT 3", style=shape.circle, location=location.abovebar,size=size.tiny,  color = color.new(bearcolorr , 10) , text="3" , textcolor = bearcolorr , editable = false)
//plotshape(short4 and ShowTEX, "GO SHORT 4", style=shape.circle, location=location.abovebar,size=size.tiny, color=color.gray, text="4")


alertcondition(long1 or short1 , 'Trend Exhausted - 1', 'Trend Exhausted | Strength - 1 ')
alertcondition(long2 or short2 , 'Trend Exhausted - 2', 'Trend Exhausted | Strength - 2 ')
alertcondition(long3 or short3 , 'Trend Exhausted - 3', 'Trend Exhausted | Strength - 3 ')
// EzAlgo SR

// Get user input
colorSup   = #04994b
colorRes   = #b4060d
strengthSR = input.int(4, "Support&Resistance Strength", 1, group="SR")
lineStyle  = input.string("Solid", "Line Style", ["Solid", "Dotted", "Dashed"], group="SR")
lineWidth  = 2
useZones   = input(true, "SR Zones", group="SR")
useHLZones = useZones
zoneWidth  = 2
expandSR   = true
// Functions
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
// Get components
rb            = 10
prd           = 284
ChannelW      = 10
label_loc     = 55
style         = lineStyle == "Solid" ? line.style_solid : lineStyle == "Dotted" ? line.style_dotted : line.style_dashed
ph            = ta.pivothigh(rb, rb)
pl            = ta.pivotlow (rb, rb)
sr_levels     = array.new_float(21, na)
prdhighest    = ta.highest(prd)
prdlowest     = ta.lowest(prd)
cwidth        = percWidth(prd, ChannelW)
zonePerc      = percWidth(300, zoneWidth)
aas           = array.new_bool(41, true)
u1            = 0.0, u1 := nz(u1[1])
d1            = 0.0, d1 := nz(d1[1])
highestph     = 0.0, highestph := highestph[1]
lowestpl      = 0.0, lowestpl := lowestpl[1]
var sr_levs   = array.new_float(21, na)
var sr_lines  = array.new_line(21, na)
var sr_linesH = array.new_line(21, na)
var sr_linesL = array.new_line(21, na)
var sr_linesF = array.new_linefill(21, na)
var sr_labels = array.new_label(21, na)
if ph or pl
    for x = 0 to array.size(sr_levels) - 1
        array.set(sr_levels, x, na)
    highestph := prdlowest
    lowestpl := prdhighest
    countpp = 0
    for x = 0 to prd
        if na(close[x])
            break
        if not na(ph[x]) or not na(pl[x])
            highestph := math.max(highestph, nz(ph[x], prdlowest), nz(pl[x], prdlowest))
            lowestpl := math.min(lowestpl, nz(ph[x], prdhighest), nz(pl[x], prdhighest))
            countpp += 1
            if countpp > 40
                break
            if array.get(aas, countpp)
                upl = (ph[x] ? high[x + rb] : low[x + rb]) + cwidth
                dnl = (ph[x] ? high[x + rb] : low[x + rb]) - cwidth
                u1 := countpp == 1 ? upl : u1
                d1 := countpp == 1 ? dnl : d1
                tmp = array.new_bool(41, true)
                cnt = 0
                tpoint = 0
                for xx = 0 to prd
                    if na(close[xx])
                        break
                    if not na(ph[xx]) or not na(pl[xx])
                        chg = false
                        cnt += 1
                        if cnt > 40
                            break
                        if array.get(aas, cnt)
                            if not na(ph[xx])
                                if high[xx + rb] <= upl and high[xx + rb] >= dnl
                                    tpoint += 1
                                    chg := true
                            if not na(pl[xx])
                                if low[xx + rb] <= upl and low[xx + rb] >= dnl
                                    tpoint += 1
                                    chg := true
                        if chg and cnt < 41
                            array.set(tmp, cnt, false)
                if tpoint >= strengthSR
                    for g = 0 to 40 by 1
                        if not array.get(tmp, g)
                            array.set(aas, g, false)
                    if ph[x] and countpp < 21
                        array.set(sr_levels, countpp, high[x + rb])
                    if pl[x] and countpp < 21
                        array.set(sr_levels, countpp, low[x + rb])
// Plot
var line highest_ = na, line.delete(highest_)
var line lowest_  = na, line.delete(lowest_)
var line highest_fill1 = na, line.delete(highest_fill1)
var line highest_fill2 = na, line.delete(highest_fill2)
var line lowest_fill1  = na, line.delete(lowest_fill1)
var line lowest_fill2  = na, line.delete(lowest_fill2)
hi_col = close >= highestph ? colorSup : colorRes
lo_col = close >= lowestpl  ? colorSup : colorRes
if enableSR
    highest_ := line.new(bar_index - 311, highestph, bar_index, highestph, xloc.bar_index, expandSR ? extend.both : extend.right, hi_col, style, lineWidth)
    lowest_  := line.new(bar_index - 311, lowestpl , bar_index, lowestpl , xloc.bar_index, expandSR ? extend.both : extend.right, lo_col, style, lineWidth)
    if useHLZones
        highest_fill1 := line.new(bar_index - 311, highestph + zonePerc, bar_index, highestph + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
        highest_fill2 := line.new(bar_index - 311, highestph - zonePerc, bar_index, highestph - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
        lowest_fill1  := line.new(bar_index - 311, lowestpl + zonePerc , bar_index, lowestpl + zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
        lowest_fill2  := line.new(bar_index - 311, lowestpl - zonePerc , bar_index, lowestpl - zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
        linefill.new(highest_fill1, highest_fill2, color.new(hi_col, 80))
        linefill.new(lowest_fill1 , lowest_fill2 , color.new(lo_col, 80))
if ph or pl
    for x = 0 to array.size(sr_lines) - 1
        array.set(sr_levs, x, array.get(sr_levels, x))
for x = 0 to array.size(sr_lines) - 1
    line.delete(array.get(sr_lines, x))
    line.delete(array.get(sr_linesH, x))
    line.delete(array.get(sr_linesL, x))
    linefill.delete(array.get(sr_linesF, x))
    if array.get(sr_levs, x) and enableSR
        line_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
        array.set(sr_lines, x, line.new(bar_index - 355, array.get(sr_levs, x), bar_index, array.get(sr_levs, x), xloc.bar_index, expandSR ? extend.both : extend.right, line_col, style, lineWidth))
        if useZones
            array.set(sr_linesH, x, line.new(bar_index - 355, array.get(sr_levs, x) + zonePerc, bar_index, array.get(sr_levs, x) + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
            array.set(sr_linesL, x, line.new(bar_index - 355, array.get(sr_levs, x) - zonePerc, bar_index, array.get(sr_levs, x) - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na))
            array.set(sr_linesF, x, linefill.new(array.get(sr_linesH, x), array.get(sr_linesL, x), color.new(line_col, 80)))

// Lux Algo Reversal Band

//func
kama(ssrc, llen) =>
    kama = 0.0
    sum_1 = math.sum(math.abs(ssrc - ssrc[1]), llen)
    sum_2 = math.sum(math.abs(ssrc - ssrc[1]), llen)
    kama := nz(kama[1]) + math.pow((sum_1 != 0 ? math.abs(ssrc - ssrc[llen]) / sum_2 : 0) * (0.288 - 0.0666) + 0.0666, 2) * (ssrc - nz(kama[1]))
    kama

//inputs
llength = input(50, title='Band Length')
bd1 = input(9, title='Frontrun Band Deviation')
bd2 = input(11, title='Initial Band Deviation')
bd3 = input(14, title='Final Band Deviation')

//logic
rg = kama(ta.tr, llength)
basis = kama(close, llength)
upper1 = basis + rg * bd1
upper2 = basis + rg * bd2
upper3 = basis + rg * bd3
lower1 = basis - rg * bd1
lower2 = basis - rg * bd2
lower3 = basis - rg * bd3

//ploting
pp1 = plot(show_rev ? upper1 : na, transp=100)
pp2 = plot(show_rev ? upper2  : na, transp=100)
pp3 = plot(show_rev ? upper3  : na, transp=100)
pp4 = plot(show_rev ? lower1  : na, transp=100)
pp5 = plot(show_rev ? lower2  : na, transp=100)
pp6 = plot(show_rev ? lower3  : na, transp=100)
fill(pp1, pp2, color=color.new(#57202c, 70))
fill(pp2, pp3, color=color.new(#57202c, 50))
fill(pp4, pp5, color=color.new(#103c3c, 70))
fill(pp5, pp6, color=color.new(#103c3c, 50))

// Candle Coloring

// Input
fastLength = input(title="Fast Length", defval=12)
slowLength = input(title="Slow Length", defval=26)
srrrc = input(title="Source", defval=close)
signalLength = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9)

// Data reference
[macd, signal, hist] = ta.macd(srrrc, fastLength, slowLength, signalLength)

// 4 level of green
greenHigh = #05df09
greenMidHigh = #05df09
greenMidLow = #388E3C
greenLow = #5f3a97

// Yellow
yellowLow = #5f3a97

// 4 level of red
redHigh = #ea0402
redMidHigh = #ea0402
redMidLow = #cc0402
redLow = #5f3a97

// Default color
candleBody = yellowLow

// Ranging trend
if hist > 0
    if hist > hist[1] and hist[1] > 0
        candleBody := greenLow
        
if hist < 0
    if hist < hist[1] and hist[1] < 0
        candleBody := redLow

// Bullish trend
if macd > 0 and hist > 0
    candleBody := greenMidLow
    
    if hist > hist[1] and macd[1] > 0 and hist[1] > 0
        candleBody := greenMidHigh
        
        if hist > hist[2] and macd[2] > 0 and hist[2] > 0
            candleBody := greenHigh

// Bearish trend
if macd < 0 and hist < 0
    candleBody := redMidLow
    
    if hist < hist[1] and macd[1] < 0 and hist[1] < 0
        candleBody := redMidHigh
        
        if hist < hist[2] and macd[2] < 0 and hist[2] < 0
            candleBody := redHigh

barcolor(candleBody) // Include suggestion by Shaheen204

// Sniper Signals


//user inputs
tres = true

sl = true

//
f = tres ? ta.ema(ta.stoch(ta.sma(ta.rsi(close, 14), 20), 10, 5, 17), 15) : ta.ema(ta.stoch(ta.sma(ta.rsi(close, 14), 20), 10, 5, 17), 1)

var alrB = false
buySnipe = f >= f[1] and f[1] < f[2]

var alrS = false
sellSnipe = f <= f[1] and f[1] > f[2]

//

plotshape(f_typee == 'Sniper Signals' ? buySnipe : na, "Buy Snipe", shape.labelup, location.belowbar, color.new(#04994b, 30), 0, "🟢", #ffffff, size = size.tiny)
plotshape(f_typee == 'Sniper Signals' ? sellSnipe : na, "Buy Snipe", shape.labeldown, location.abovebar, color.new(#d13b6d, 30), 0, "🔴", #ffffff, size = size.tiny)


// sl
ndd = bar_index
ldd = close - (ta.atr(30) * 1.5)

line s = na
if buySnipe
    s := sl and f_typee == 'Sniper Signals' ?  line.new(ndd, ldd, ndd + 21, ldd, extend = extend.none, color = #d13b6d, style = line.style_dashed, width = 1) : na

slPrice = ta.valuewhen(buySnipe, l, 1)

if sellSnipe
    alrS := true
if buySnipe
    alrS := false

slSignal = ta.crossunder(close, slPrice) and not alrS

plotshape(f_typee == 'Sniper Signals' ? slSignal : na, "SL Exit", shape.xcross, color = color.new(#2f48f9, 75))

// Dashboard

showDashboard     = input(true, "Show Dashboard", group="TREND DASHBOARD")
locationDashboard = input.string("Middle Right", "Table Location", ["Top Right", "Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center", "Top Left", "Middle Left", "Bottom Left"], group="TREND DASHBOARD")
tableTextColor    = input(color.new(#b1b3be, 2), "Table Text Color", group="TREND DASHBOARD")
tableBgColor      = input(color.new(#232534,65), "Table Background Color", group="TREND DASHBOARD")
sizeDashboard     = input.string("Tiny", "Table Size", ["Large", "Normal", "Small", "Tiny"], group="TREND DASHBOARD")

// Functions
f_chartTfInMinutes() =>
    float _resInMinutes = timeframe.multiplier * (
      timeframe.isseconds ? 1. / 60             :
      timeframe.isminutes ? 1.                  :
      timeframe.isdaily   ? 60. * 24            :
      timeframe.isweekly  ? 60. * 24 * 7        :
      timeframe.ismonthly ? 60. * 24 * 30.4375  : na)

// Get components
emae  = ta.ema(close, 144)
emaBull = close > emae
equal_tf(res) => str.tonumber(res) == f_chartTfInMinutes()
higher_tf(res) => str.tonumber(res) > f_chartTfInMinutes()
too_small_tf(res) => (timeframe.isweekly and res=="1") or (timeframe.ismonthly and str.tonumber(res) < 10)
securityNoRep1(sym, res, srce) =>
    bool bulle = na
    bulle := equal_tf(res) ? srce : bulle
    bulle := higher_tf(res) ? request.security(sym, res, srce, barmerge.gaps_off, barmerge.lookahead_on) : bulle
    bull_array = request.security_lower_tf(syminfo.tickerid, higher_tf(res) ? str.tostring(f_chartTfInMinutes()) : too_small_tf(res) ? (timeframe.isweekly ? "3" : "10") : res, srce)
    if array.size(bull_array) > 1 and not equal_tf(res) and not higher_tf(res)
        bulle := array.pop(bull_array)
    array.clear(bull_array)
    bulle
TF1Bull   = securityNoRep1(syminfo.tickerid, "1"   , emaBull)
TF3Bull   = securityNoRep1(syminfo.tickerid, "3"   , emaBull)
TF5Bull   = securityNoRep1(syminfo.tickerid, "5"   , emaBull)
TF15Bull  = securityNoRep1(syminfo.tickerid, "15"  , emaBull)
TF30Bull  = securityNoRep1(syminfo.tickerid, "30"  , emaBull)
TF60Bull  = securityNoRep1(syminfo.tickerid, "60"  , emaBull)
TF120Bull = securityNoRep1(syminfo.tickerid, "120" , emaBull)
TF240Bull = securityNoRep1(syminfo.tickerid, "240" , emaBull)
TF480Bull = securityNoRep1(syminfo.tickerid, "480" , emaBull)
TFDBull   = securityNoRep1(syminfo.tickerid, "1440", emaBull)

var dashboard_loc  = locationDashboard == "Top Right" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
var dashboard      = showDashboard ? table.new(dashboard_loc, 2, 15, tableBgColor, #404250, 1, tableBgColor, 1) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column, row, txt, 0, 0, signal ? #737581 : tableTextColor, text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column, row, col)
if barstate.islast and showDashboard
    dashboard_cell(0, 0 , "VitAlgo")
    dashboard_cell(0, 1 , "Current Position")
    dashboard_cell(0, 2 , "Current Trend")
    dashboard_cell(0, 3 , "Volume")
    dashboard_cell(0, 4 , "Timeframe")
    dashboard_cell(0, 5 , "1 min:")
    dashboard_cell(0, 6 , "3 min:")
    dashboard_cell(0, 7 , "5 min:")
    dashboard_cell(0, 8 , "15 min:")
    dashboard_cell(0, 9 , "30 min:")
    dashboard_cell(0, 10, "1 H:")
    dashboard_cell(0, 11, "2 H:")
    dashboard_cell(0, 12, "4 H:")
    dashboard_cell(0, 13, "8 H:")
    dashboard_cell(0, 14, "Daily:")
    dashboard_cell(1, 0 , "Premium")
    dashboard_cell(1, 1 , emaBull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 1, emaBull ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 2 , str.tostring(math.round_to_mintick(volume)))
    dashboard_cell(1, 3 , "Trends")
    dashboard_cell(1, 4 , TF1Bull   ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 4 , TF1Bull   ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 5 , TF3Bull   ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 5 , TF3Bull   ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 6 , TF5Bull   ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 6 , TF5Bull   ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 7 , TF15Bull  ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 7 , TF15Bull  ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 8 , TF30Bull  ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 8 , TF30Bull  ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 9, TF60Bull  ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 9, TF60Bull  ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 10, TF120Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 10, TF120Bull ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 11, TF240Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 11, TF240Bull ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 12, TF480Bull ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 12, TF480Bull ? color.new(#125e5a, 10) : color.new(#672230, 10))
    dashboard_cell(1, 13, TFDBull   ? "Bullish" : "Bearish", true), dashboard_cell_bg(1, 13, TFDBull   ? color.new(#125e5a, 10) : color.new(#672230, 10))